let canvas1 = document.getElementById('canvas1');
  canvas1.width = window.innerWidth;
  canvas1.height = window.innerHeight;
  let ctx = canvas1.getContext('2d');
  let w = canvas1.width;
  let h = canvas1.height;

  document.getElementById('files').onchange = function(){
    let audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    let file = this.files[0];
    let fr = new FileReader();
    fr.onload = function(e){
      audioCtx.decodeAudioData(e.target.result, function(buffer){
        play(buffer, audioCtx);
      }, function(err){
        console.log(err);
      })
    }
    // audioCtx.onstatechange = function() {
    //   console.log(audioCtx.state);
    // }
    audioCtx.addEventListener('statechange', function(){
      console.log('statechange', audioCtx.state);
    })

    fr.readAsArrayBuffer(file);
  }
  let analyserNode;
  let sourceArr;

  let count = 0;
  let stoped = false;

  function play(buffer, audioCtx){
    analyserNode = audioCtx.createAnalyser();

    let audioBufferSourceNode = audioCtx.createBufferSource();
    audioBufferSourceNode.addEventListener('ended', function(){
      console.log('ended');
      cancelAnimationFrame(draw);
      stoped = true;
    })
    audioBufferSourceNode.buffer = buffer;
    audioBufferSourceNode.connect(audioCtx.destination);
    audioBufferSourceNode.connect(analyserNode);
    audioBufferSourceNode.loop = false;
    audioBufferSourceNode.start(0);

    sourceArr = new Uint8Array(analyserNode.frequencyBinCount);
    draw()
  }

  function draw(){
    if(stoped) return;
    // analyserNode.getByteFrequencyData(sourceArr);
    analyserNode.getByteTimeDomainData(sourceArr);
    // console.log(sourceArr);
    // requestAnimationFrame(draw);
    console.log(count++, analyserNode.smoothingTimeConstant);
    ctx.fillStyle = 'rgb(0, 0, 0)';
    ctx.fillRect(0, 0, w, h);

    let barWidth = (w / analyserNode.frequencyBinCount) * 2.5;
    let barHeight;
    let x = 0;

    // for(let i = 0; i < analyserNode.frequencyBinCount; i++){
    //   barHeight = sourceArr[i];
    //   ctx.fillStyle = "rgb(" + (barHeight + 100) + ',50,50)';
    //   ctx.fillRect(x, h - barHeight/2, barWidth, barHeight/2);

    //   x += barWidth;
    // }

    for(let i = 0; i < analyserNode.frequencyBinCount; i = i + 1000){
      ctx.fillStyle = 'rgb(0, 0, 0)';
      ctx.fillRect(0, 0, w, h);
      ctx.fillStyle = 'rgb(234, 234, 234)';
      let size = 128 + ((sourceArr[i] - 128) / 128) * 100;
      ctx.fillRect(w/2 - size /2, h/2 - size/2, size, size);
    }


    requestAnimationFrame(draw)
  }